package jmu.edu.yjc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jmu.edu.yjc.Utils.BeanCopyUtil;
import jmu.edu.yjc.Utils.RedisCache;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.dto.ArticleDto;
import jmu.edu.yjc.domain.entity.Article;
import jmu.edu.yjc.domain.entity.Category;
import jmu.edu.yjc.domain.entity.User;
import jmu.edu.yjc.domain.vo.PageVo;
import jmu.edu.yjc.domain.vo.article.*;
import jmu.edu.yjc.mapper.ArticleMapper;
import jmu.edu.yjc.service.ArticleService;
import jmu.edu.yjc.service.CategoryService;
import jmu.edu.yjc.service.user.UserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文章表(Article)表服务实现类
 *
 * @author makejava
 * @since 2023-02-05 15:52:35
 */
@Service("articleService")
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Resource
    @Lazy
    private CategoryService categoryService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private UserService userService;
    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId, String searchString) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        Category announcement = categoryService.getByCategoryName("社区公告");
        wrapper.ne(Article::getCategoryId,announcement.getId());
        wrapper.eq(categoryId!= null, Article::getCategoryId,categoryId);
        wrapper.and(StringUtils.hasText(searchString), wq -> {
            wq.like(Article::getTitle,searchString).or().like(Article::getSummary,searchString);
        });
        Integer res = (pageNum-1)*pageSize;
        Integer tar = (pageNum)*pageSize;
        List<ArticleDetailVo> articleDetailVos = baseMapper.articleList(res, tar, announcement.getId(), categoryId, searchString);
        return ResponseResult.okResult(new PageVo(articleDetailVos,(long) count(wrapper)));
    }

    @Override
    public ResponseResult getArticle(Long id) {
        //根据id查询文章
        Article article = getById(id);
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());
        //封装Vo
        ArticleDetailVo articleDetailVo = BeanCopyUtil.copyBeans(article, ArticleDetailVo.class);
        //根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        User user = userService.getById(article.getCreateBy());
        ArticleUserVo articleUserVo = BeanCopyUtil.copyBeans(user,ArticleUserVo.class);
        articleDetailVo.setArticleUserVo(articleUserVo);
        Category category = categoryService.getById(categoryId);
        if(category!=null){
            articleDetailVo.setCategoryName(category.getName());
        }

        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应articleId的浏览量
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();
    }
    @Transactional
    @Override
    public ResponseResult addArticle(ArticleDto articleDto) {
        Article article = BeanCopyUtil.copyBeans(articleDto,Article.class);
        //调用save方法，mybatis plus会自动保存id到对象中
        save(article);
        //往redis增加浏览量
        redisCache.setCacheMapValue("article:viewCount",article.getId().toString(),0);
        return ResponseResult.okResult();
    }

    /**
     *
     * @param article 查询信息
     * @param pageNum 页码
     * @param pageSize 页面大小
     * @param userId 查询者id
     * @return 文章信息
     */
    @Override
    public ResponseResult selectArticlePage(Article article, Integer pageNum, Integer pageSize, Integer userId) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(StringUtils.hasText(article.getTitle()),Article::getTitle, article.getTitle());
        queryWrapper.like(StringUtils.hasText(article.getSummary()),Article::getSummary, article.getSummary());
        queryWrapper.eq(userId!=null,Article::getCreateBy,userId);
        Page<Article> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page,queryWrapper);

        //转换成VO
        List<ArticleDetailVo> articleDetailVos = BeanCopyUtil.copyBeanList(page.getRecords(), ArticleDetailVo.class);
        //查询创建者信息,分类名
        for (ArticleDetailVo vo : articleDetailVos) {
            User user = userService.getById(vo.getCreateBy());
            ArticleUserVo articleUserVo = BeanCopyUtil.copyBeans(user, ArticleUserVo.class);
            Category category = categoryService.getById(vo.getCategoryId());
            vo.setCategoryName(category.getName());
            vo.setArticleUserVo(articleUserVo);
        }
        return ResponseResult.okResult(new PageVo(articleDetailVos,page.getTotal()));
    }

    @Override
    public ResponseResult getAnnouncement(Integer pageNum, Integer pageSize, String title) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(title),Article::getTitle,title);
        Category category = categoryService.getAnnouncementCId();
        wrapper.eq(Article::getCategoryId,category.getId());
        wrapper.orderByDesc(Article::getCreateTime);
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,wrapper);
        List<Article> records = page.getRecords();
        List<AnnouncementVo> announcementVos = BeanCopyUtil.copyBeanList(records, AnnouncementVo.class);
        for (AnnouncementVo vo : announcementVos) {
            vo.setCategoryName(category.getName());
        }
        return ResponseResult.okResult( new PageVo(announcementVos, page.getTotal()));
    }

    @Transactional
    @Override
    public ResponseResult getArticleAndUpdateViewCount(Long id) {
        Article article =getById(id);
        Long viewCount = article.getViewCount();
        viewCount += 1;
        article.setViewCount(viewCount);
        Article update = new Article();
        update.setViewCount(viewCount);
        update.setId(article.getId());
        updateById(update);
        ArticleDetailVo articleVo = BeanCopyUtil.copyBeans(article, ArticleDetailVo.class);
        User user = userService.getById(articleVo.getCreateBy());
        ArticleUserVo articleUserVo = BeanCopyUtil.copyBeans(user, ArticleUserVo.class);
        articleVo.setArticleUserVo(articleUserVo);
        return ResponseResult.okResult(articleVo);
    }

    @Override
    public ResponseResult getHotArticle() {
        Category announcement = categoryService.getByCategoryName("社区公告");
        Category news = categoryService.getByCategoryName("新闻热点");
        Category work = categoryService.getByCategoryName("工作动态");
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Article::getCategoryId,announcement.getId());
        wrapper.select(Article::getId,Article::getCategoryId,Article::getTitle,Article::getViewCount,Article::getCreateTime,Article::getThumbnail);
        wrapper.orderByDesc(Article::getCreateTime);
        wrapper.last("limit 5");
        List<Article> announcementList = list(wrapper);
        wrapper.clear();
        wrapper.eq(Article::getCategoryId,news.getId());
        wrapper.select(Article::getId,Article::getCategoryId,Article::getTitle,Article::getViewCount,Article::getCreateTime,Article::getThumbnail);
        wrapper.orderByDesc(Article::getViewCount);
        wrapper.last("limit 5");
        List<Article> newsList = list(wrapper);
        wrapper.clear();
        wrapper.eq(Article::getCategoryId,work.getId());
        wrapper.select(Article::getId,Article::getCategoryId,Article::getTitle,Article::getViewCount,Article::getCreateTime,Article::getThumbnail);
        wrapper.orderByDesc(Article::getCreateTime);
        wrapper.last("limit 5");
        List<Article> workList = list(wrapper);
        return ResponseResult.okResult(new DashBoardVo(announcementList, newsList, workList));
    }

    @Override
    public ResponseResult getRecommendArticle() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        Category announcement = categoryService.getByCategoryName("社区公告");
        queryWrapper.ne(Article::getCategoryId,announcement.getId());
        queryWrapper.orderByDesc(Article::getViewCount);
        queryWrapper.select(Article::getId,Article::getTitle,Article::getViewCount);
        queryWrapper.last("limit 10");
        return ResponseResult.okResult(list(queryWrapper));
    }

    @Override
    public ResponseResult getSearchArticle(String search) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        Category announcement = categoryService.getByCategoryName("社区公告");
        wrapper.ne(Article::getCategoryId,announcement.getId())
                .and(wq -> {
                    wq.like(StringUtils.hasText(search),Article::getTitle,search)
                            .or()
                            .like(StringUtils.hasText(search),Article::getSummary,search);
                });
        wrapper.select(Article::getId,Article::getTitle);
        wrapper.orderByDesc(Article::getViewCount);
        wrapper.last("limit 10");
        return ResponseResult.okResult(list(wrapper));
    }

}
